<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 * Default view for listing currently contained files.
 *  
 * @package com_musashi
 * @author Daniel Torres
 */
 
// Make sure we have access to this page
defined('_JEXEC') or die ('Restricted access. Sorry');
  
// Add the stylesheet for this page
JHTML::_('stylesheet','base.css','components/com_musashi/views/common/');
JHTML::_('stylesheet','default.css','components/com_musashi/views/files/tmpl/');
JHTML::_('script','dropdown.js','components/com_musashi/views/common/');
JHTML::_('script','jquery-1.5.min.js','components/com_musashi/views/common/');


/**
 *  Checks to see if there is a message from a previous action. Clears the flag if necessary
 */
function getActionResult( $actionFlag )
{
    $session =& JFactory::getSession();
    
    // Get previous message, then clear
    $msg = $session->get($actionFlag,'');
    $session->set($actionFlag,'');
    
    return $msg;
}

/**
 *  Receives a file size, and returns a human-readable number
 */
function formatFilesize( $a_size )
{
    if( is_numeric($a_size))
    {
        // For more than 1 Kb
        if( $a_size > 1048576){
            return round(abs( $a_size * 100 / 1048576 ) / 100,2).' MB';
        } else {
            return round(abs( $a_size * 100 / 1024) / 100,2).' KB';
        }
    }
    else
    {
        return "";
    }
    
    
}

// We'll be needing this model
$model =& $this->getModel();

// The array of all contained folders
$allFolders = $model->getAllFolders();

// Description and data for the requested folder
$folderID = JRequest::getInt('fid',-1);

// If an ID hasn't been requested, make sure there is a root folder, and
// set this as the required component
if( $folderID == -1 )
{
    $model->verifyRootFolder();
    $root = $model->getFolderData('root');
    
    if( $root != null )
    {
        $folderID = $root->id;        
    }
}

// Get all the files for the current folder
$files = $model->getFilesForFolder( $folderID );

?>

<script language="javascript" type="text/javascript">
<!--

// jQuery in compatibility mode
var _jq = jQuery.noConflict();

// Deletes our current folder
function deleteFolder()
{
    <?php    
    // Can't delete a folder that's not empty
    if( count($files) > 0){
        ?>
        alert('Cannot delete folder: It contains one or more files');
        <?php
    }
    else
    {
        ?>
        if (confirm('Delete current folder: Are you sure?'))
        {
            newLocation = "<?php echo JRoute::_('index.php?option=com_musashi&controller=files&task=delFolder&fid='.$folderID.'&rn='.rand(1,9999)); ?>";
            document.location.href = newLocation;
        }
        <?php
    }
    ?>
}

// Reloads the page with the provided folder data
function loadFolder( selection )
{
    // Load the new folder
    newLocation = "<?php echo JRoute::_('index.php?option=com_musashi&controller=files&view=files'); ?>"+"&fid="+selection.value;
    document.location.href = newLocation;
}

// Checks to make sure the proposed folder doesn't already exist in our database
function testFolder()
{
    form = document.newDirForm;
    
    if (form.name.value == "")
    {
        alert("Please provide a name for this folder");
        return false;        
    }
    
    var nameArray = [];
    <?php        
        foreach ($allFolders as $folderData )
        {
            echo "nameArray.push('".$folderData[1]."');";
        }    
    ?>
    
    // Test
    if (nameArray.indexOf(form.name.value) != -1){
        alert("A folder of the same name exists already. Please choose something different");
        return false;
    }
    
    return true;
}

// A file has been selected for upload
function fileSelected()
{
    var file = document.getElementById('uploadingFile').files[0];
    if (file)
    {
        var fileSize = 0;
        if( file.size > 1048576 ) {
            fileSize = (Math.round( file.size * 100 / 1048576 ) / 100).toString() + 'MB';
        } else {
            fileSize = (Math.round( file.size * 100 / 1024) / 100 ).toString() + 'KB';
        }
        
        var fileType = file.type;
        if (file.type == ""){
            fileType = "unknown";
        }
        
        document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
        document.getElementById('fileType').innerHTML = 'Type: ' + fileType;
        
        // Show this information
        document.getElementById('new-file-info').style.display="block";
    }
    
}

// Starts the file upload process
function startUpload()
{
    // Do some file testing first
    var file = document.getElementById('uploadingFile').files[0];
    if( file )
    {        
        // Create a transmision object for this file
        var request  = new XMLHttpRequest();
        var formData = new FormData(document.getElementById('new-file-form'));
        
        // Add some listeners for the file transmision event
        request.upload.addEventListener('progress',uploadProgress,false);
        request.addEventListener('load',uploadComplete,false);
        request.addEventListener('error',uploadFailed,false);
        request.addEventListener('abort',uploadCanceled,false);
        
        // Start the transmision event
        request.open("POST",'<?php echo JRoute::_('index.php?option=com_musashi&controller=files&task=addFile'); ?>');
        request.send(formData);        
    }
    else
    {
        alert('Please select a file to upload');
    }
    
}

// Event handler for upload progress report
function uploadProgress(evt)
{
    var progressNode = document.getElementById('fileProgress');
    if (evt.lengthComputable)
    {
        progressNode.innerHTML = 'Progress: ' + (Math.round( evt.loaded * 100 / evt.total )).toString() + ' %';
    }
    else
    {
        progressNode.innerHTML = 'Progress: Unknown';
    }
}

// Event handler for completed events
function uploadComplete( evt )
{
    // Simply reset to reflect the change
    newLocation = "<?php echo JRoute::_('index.php?option=com_musashi&controller=files&view=files&fid='.$folderID.'&rn='.rand(1,9999),false); ?>";
    document.location.href = newLocation;
}

// Failed events
function uploadFailed(evt)
{
    alert("An error was detected while uploading the file, please try again");
}
function uploadCanceled(evt)
{
    alert("The upload operation has been canceled by the user, or the conection to the server has been lost");
}


// State vars for our sections
var isAddFileVisible   = false;
var isAddFolderVisible = false;

function setFileAndFolderVisibility( fileIsVisible, folderIsVisible )
{
    if(fileIsVisible){
        _jq('#new-file').show();
        isAddFileVisible = true;
    } else {
        _jq('#new-file').hide();
        isAddFileVisible = false;
    }
    
    if(folderIsVisible){
        _jq('#new-folder').show();
        isAddFolderVisible = true;
    } else {
        _jq('#new-folder').hide();
        isAddFolderVisible = false;
    }
}

// Show the different sections
_jq(function(){
    _jq('#opt-addfile').click(function(){        
        if( !isAddFileVisible ) {
            setFileAndFolderVisibility( true, false );
        }        
        return false;        
    });    

    _jq('#opt-addfolder').click(function(){
        
        if( !isAddFolderVisible ) {
            setFileAndFolderVisibility( false, true );
        }
        
        return false;        
    });    
});


// Cancel file loading
_jq(function(){
    _jq('#btn-cancelFile').click(function(){
        setFileAndFolderVisibility(false,false);
    });
    _jq('#btn-cancelFolder').click(function(){
        setFileAndFolderVisibility(false,false);
    });
});


-->
</script>

<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->


<musashiContent id='content' class='body'>
    <header id="title" class="body">
        <div class="name">
            <h1>Files and Folders</h1>
        </div>
        <div class="description">
            <p>A collection of files stored in the system, and classified by folder. Add
            files or folders as necessary, and use them as reference for your shows or
            messages, or keep them here as an auxiliary database</p>
        </div>
    </header>
    
    <?php

    // -------------------------------------------------------------------------
    // Previous action result
    // -------------------------------------------------------------------------
    $previousMessage = getActionResult('errorMessage');
    if( $previousMessage != '')
    {?>
        <div class="error"><?php echo $previousMessage; ?></div>
    <?php        
    }
    ?>
    
    <div id="folder-container">
        <form id="folder-selection">
            <select name="folderSelection" onchange="loadFolder(this);">
                <?php
                $folderDesc = "";
                $enableDel  = true;
                foreach( $allFolders as $folderData )
                {
                    // Is this the folder we're looking for?                                
                    if( $folderData[0] == $folderID )
                    {
                        echo '  <option value="'.$folderData[0].'" selected>'.$folderData[1].'</option>';
                        $folderDesc = $folderData[2];
                        
                        // Disable deletes for the root folder
                        if ($folderData[1] == 'root'){
                            $enableDel = false;
                        }
                    }
                    else
                    {
                        echo '  <option value="'.$folderData[0].'">'.$folderData[1].'</option>';
                    }
                }
                ?>
            </select>
            <h2><?php echo $folderDesc; ?></h2>
        </form>
        
        <div id="folder-options">
            <ol>
                <li>
                    <a href="#" id="opt-addfile">Add a file</a>
                </li>
                <li>
                    <a href="#" id="opt-addfolder">New folder</a>
                </li>
                <li>
                <?php
                    if ($enableDel)
                    {?>
                        <a href="#" onclick="deleteFolder();">Delete this folder</a>
                     <?php   
                    }
                    else
                    {?>
                        <a href="#" style="color:#cacaca;">Delete this folder</a>
                    <?php 
                    }
                ?>
                </li>                       
            </ol>
        </div>
        
        <div id="content-area">
        
            <!-- New folder div -->
            <div id="new-folder" style="display:none;">
                <form class="new-folder-form" method="post" action="<?php JRoute::_('index.php'); ?>" name="newDirForm"  onsubmit="return testFolder()">
                    <fieldset>
                        <ol>
                            <li>
                                <label for="name">Folder name:</label>
                                <input name="name" maxlength="10" size="10">
                            </li>
                            <li>
                                <label for="description">Description:</label>
                                <input name="description" maxlength="45" size="45">
                            </li>
                            <li>
                                <button type="submit" style="margin-left:26em;">Add Folder</button>
                                <button type="button" id='btn-cancelFolder'>Cancel</button>
                            </li>
                        </ol>
                    </fieldset>
                    <input type="hidden" name="option"     value="com_musashi" />
                    <input type="hidden" name="task"       value="addFolder" />
                    <input type="hidden" name="controller" value="files" />
                </form>            
            </div>
            
            <!-- New file div -->
            <div id="new-file" style="display:none">
                <form class="new-file-form" id='new-file-form' method="post" enctype="multipart/form-data" >
                    <fieldset>
                        <ol>
                            <li>
                                <label for="name">Filename</label>
                                <input type="file" style="margin-left:10px;" id="uploadingFile" name="userfile"  onchange="fileSelected();"/>
                            </li>
                            <li>
                                <label for="description">Description</label>
                                <input name="description" maxlength="45" size="45" />
                            </li>
                            <li>
                                <button type="button" style="margin-left:9em;" onclick="startUpload();" >Upload</button>
                                <button type="button" id='btn-cancelFile'>Cancel</button>
                            </li>                                
                        </ol>
                    </fieldset>
                    <input type="hidden" name="folderID" value="<?php echo $folderID; ?>">
                    <input type="hidden" name="option" value="com_musashi" />
                    <input type="hidden" name="task" value="addFile" />
                    <input type="hidden" name="controller" value="files" />
                </form>
                <div class="new-file-info" id='new-file-info' style="display:none">
                    <h2 id='fileSize' >File Size: 32 mb</h2>
                    <h2 id='fileType' >SomeType</h2>
                    <h3 id='fileProgress'>Progress: 0%</h3>
                </div>
            </div>
            
            <!--- The files themselves -->
            <div id="file-container">
                <?php
                // Get all the files for the requested folder
                $files = $model->getFilesForFolder( $folderID );
                if (count($files) == 0)
                {
                    ?>
                    <div class="nofiles"><h4>Empty folder</h4></div>
                    <?php
                }
                else
                {
                    $usrPath = $model->getUploadPath();
                    echo '<ol>';
                    foreach( $files as $fileData )
                    {
                        $fileSize = filesize($usrPath.$model->makePhysicalFilename( $fileData[0], $folderID ));
                        ?>
                        <li>
                            <a href="<?php echo JRoute::_('index.php?option=com_musashi&controller=files&task=download&file='.$fileData[0].'&fid='.$folderID); ?>"><?php echo $fileData[1].' ('.formatFilesize($fileSize).')'; ?></a>
                            <h5><?php
                            if ($fileData[2] != ""){
                                echo $fileData[2];
                            } else {
                                echo "No description";
                            }                            
                            ?></h5>
                            <a onclick="return confirm('Are you sure?');" href="<?php echo JRoute::_('index.php?option=com_musashi&controller=files&task=delFile&file='.$fileData[0].'&fid='.$folderID); ?>"><h3>delete</h3></a>
                        </li>
                        <?php                        
                    }
                    echo '</ol>';                    
                }
                ?>                
            </div>
        </div>
    </div>
    
    <!-- Footer. Display syndication, and some copyright information -->
    <footer id="footer" class="body">
        <div class="footer-data">
            <h2>The Musashi Project</h2>
            <h3>A Framework for Managing Your Group</h3>
            <p>(c)2010 - The Musashi Project</p>                    
        </div>
    </footer>
    
</musashiContent>















